package changepassword;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

@SuppressWarnings("serial")
public class ChangePasswordServlet extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws IOException {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Key accountKey = KeyFactory.createKey("Accounts", "accountName");
		String newPassword = req.getParameter("newPassword");
		String oldPassword = req.getParameter("oldPassword");
		// javascript used to check if the confirm password is the same as new password
		
		Query query = new Query("Account", accountKey).addFilter("password", FilterOperator.EQUAL, oldPassword);
		Entity user = datastore.prepare(query).asSingleEntity();
		if (user != null) {
			user.setProperty("password", newPassword);
			datastore.put(user);
			resp.sendRedirect("/profile.jsp");
		} else {
			// error
			resp.sendRedirect("/profile.jsp?Error=true");
		}
	}
}
